package com.mysoft.gfyx.marketdevelop.service.impl;

import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.common.manifest.MySoftManifestProvider;
import com.mysoft.framework.common.util.JsonUtil;
import com.mysoft.framework.modeling.dto.Filter;
import com.mysoft.gfyx.common.time.TimeService;
import com.mysoft.gfyx.marketdevelop.controller.dto.GetDetailDataRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.GetDeveloperDataService;
import com.mysoft.gfyx.marketdevelop.mip.dto.BaseTjFilterDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.BaseTjListResponseDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.GetDeveloperFilterDataRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.GetDeveloperSortDto;
import com.mysoft.gfyx.marketdevelop.service.*;
import com.mysoft.gfyx.marketdevelop.service.dto.CommonGraphDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DeveloperGraphServiceImp implements DeveloperGraphService {

    @Autowired
    private DeveloperService developerService;

    @Autowired
    private GetDeveloperDataService getDeveloperDataService;

    @Autowired
    private ProcurementRequirementService procurementRequirementService;

    @Autowired
    private DeveloperCooperatorService developerCooperatorService;

    @Autowired
    private DeveloperTakeLandService developerTakeLandService;

    @Autowired
    private DeveloperCommencePermitService developerCommencePermitService;

    @Autowired
    private MohurdProjectService mohurdProjectService;

    @Autowired
    private TimeService timeService;

    public CommonGraphDto getCommonGraph(String creditCode) {

        // ToDo 先获取顶级公司的code，再往下计算
        return getCommonGraph(creditCode, "");
    }

    public CommonGraphDto getCommonGraph(String creditCode, String topCreditCode) {
        Set<String> scanBasePackages = MySoftManifestProvider.getEntityResources();
        System.out.println("-------------------------------------哈哈哈哈哈哈------------------------");
        System.out.println(JsonUtil.toString(scanBasePackages));
        CommonGraphDto commonGraphDto = new CommonGraphDto();
        commonGraphDto.setCompany(getCompanyData(creditCode));

        if (!creditCode.equals(topCreditCode)) {
            commonGraphDto.setTopCompany(getCompanyData(topCreditCode));
        }

        return commonGraphDto;
    }

    protected CommonGraphDto.CompanyData getCompanyData(String creditCode) {
        CommonGraphDto.CompanyData companyData = new CommonGraphDto.CompanyData();

        // 招标
        putPurchasesIn(companyData, creditCode);

        // 中标
        putCooperatorsIn(companyData, creditCode);

        return companyData;
    }

    protected void putPurchasesIn(CommonGraphDto.CompanyData companyData, String creditCode) {
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_PROCUREMENT_REQUIREMENT_WITH_INVESTMENT);
        dto.setPage(1);
        dto.setPage_size(2000);
        dto.addFilterDtos("organizing_code", BaseTjFilterDto.OPERATE_EQUAL, creditCode, DeveloperService.TABLE_PROCUREMENT_REQUIREMENT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_NONE);

        String latestData = timeService.getYearsAgo(1, new Date(), "yyyy-MM-dd HH:mm:ss");
        dto.addFilterDtos("publish_time", BaseTjFilterDto.OPERATE_LARGER_EQUAL, latestData, DeveloperService.TABLE_PROCUREMENT_REQUIREMENT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_AND);

        // 排序
        ArrayList<GetDeveloperSortDto> sorts = new ArrayList<>();
        GetDeveloperSortDto sort = new GetDeveloperSortDto();
        sort.setSort_type(GetDeveloperSortDto.SORT_DESC);
        sort.setAttribute_name("publish_time");
        sort.setTable_name(DeveloperService.TABLE_PROCUREMENT_REQUIREMENT_WITH_INVESTMENT);
        sorts.add(sort);
        dto.setSorts(sorts);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        if (res.getData() == null || res.getData().getList() == null) {
            return;
        }

        res.getData().getList().forEach(p -> {
            CommonGraphDto.RelatedBid relatedBid = new CommonGraphDto.RelatedBid();

            relatedBid.setId(p.getItem().get("id").toString());
            relatedBid.setPrincipal(p.getItem().get("ower").toString());
            relatedBid.setPrincipalMobile(p.getItem().get("ower_mobile").toString());
            relatedBid.setTitle(p.getItem().get("title").toString());
            relatedBid.setCompany(p.getItem().get("sub_developer_name").toString());
            relatedBid.setSource(p.getItem().get("data_source_code").toString());

            companyData.getRelatedBids().add(relatedBid);
        });
    }

    protected void putCooperatorsIn(CommonGraphDto.CompanyData companyData, String creditCode) {

        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_COOPERATOR_WITH_INVESTMENT);
        dto.setPage(1);
        dto.setPage_size(2000);
        dto.addFilterDtos("organizing_code", BaseTjFilterDto.OPERATE_EQUAL, creditCode, DeveloperService.TABLE_COOPERATOR_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_NONE);

        // 排序
        ArrayList<GetDeveloperSortDto> sorts = new ArrayList<>();
        GetDeveloperSortDto sort = new GetDeveloperSortDto();
        sort.setSort_type(GetDeveloperSortDto.SORT_DESC);
        sort.setAttribute_name("begin_date");
        sort.setTable_name(DeveloperService.TABLE_COOPERATOR_WITH_INVESTMENT);
        sorts.add(sort);
        dto.setSorts(sorts);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        if (res.getData() == null || res.getData().getList() == null) {
            return;
        }

        res.getData().getList().forEach(p -> {
            CommonGraphDto.RelatedCooperator relatedCooperator = new CommonGraphDto.RelatedCooperator();

            relatedCooperator.setId(p.getItem().get("sub_organizing_code").toString());
            relatedCooperator.setCooperateDate(p.getItem().get("begin_date").toString());
            relatedCooperator.setContactsCount(0);
            relatedCooperator.setName(p.getItem().get("sub_developer_name").toString());
            relatedCooperator.setProject(p.getItem().get("project_name").toString());
            relatedCooperator.setType(p.getItem().get("project_level").toString());

            companyData.getRelatedCooperators().add(relatedCooperator);
        });
    }

    protected void putWinBidIn(CommonGraphDto.CompanyData companyData, String creditCode) {

        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_WINBID);
        dto.setPage(1);
        dto.setPage_size(2000);
        dto.addFilterDtos("organizing_code", BaseTjFilterDto.OPERATE_EQUAL, creditCode, DeveloperService.TABLE_WINBID, BaseTjFilterDto.ASSOCIATE_NONE);

        // 排序
        ArrayList<GetDeveloperSortDto> sorts = new ArrayList<>();
        GetDeveloperSortDto sort = new GetDeveloperSortDto();
        sort.setSort_type(GetDeveloperSortDto.SORT_DESC);
        sort.setAttribute_name("publish_time");
        sort.setTable_name(DeveloperService.TABLE_WINBID);
        sorts.add(sort);
        dto.setSorts(sorts);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        if (res.getData() == null || res.getData().getList() == null) {
            return;
        }

        res.getData().getList().forEach(p -> {
            CommonGraphDto.RelatedCooperator relatedCooperator = new CommonGraphDto.RelatedCooperator();

            relatedCooperator.setId(p.getItem().get("id").toString());
            relatedCooperator.setCooperateDate(p.getItem().get("publish_time").toString());
            if (p.getItem().get("ower_contact") == null || p.getItem().get("ower_contact").toString().equals("")) {
                relatedCooperator.setContactsCount(0);
            } else {
                String[] contacts = p.getItem().get("ower_contact").toString().split(";");
                relatedCooperator.setContactsCount(contacts.length);
            }

            relatedCooperator.setName(p.getItem().get("ower_unit").toString());
            relatedCooperator.setProject(p.getItem().get("title").toString());
            relatedCooperator.setType(p.getItem().get("type").toString());

            companyData.getRelatedCooperators().add(relatedCooperator);
        });
    }

    public CommonGraphDto getPurchaseGraph(String purchaseId) {
        Map<String, Object> purchase = procurementRequirementService.getPurchaseByPurchaseId(purchaseId);
        if (purchase.get("id") == null || purchase.get("organizing_code") == null || purchase.get("organizing_code").equals("")) {
            throw new BusinessLogicException("数据获取中");
        }

        Map<String, Object> companyData = developerService.getDeveloperMainData(purchase.get("organizing_code").toString());
        String topDeveloperCode;
        if (companyData.get("is_top_company_contain_developer").equals("是")) {
            topDeveloperCode = companyData.get("top_organizing_code").toString();
        } else {
            topDeveloperCode = companyData.get("organizing_code").toString();
        }

        CommonGraphDto commonGraphDto = getCommonGraph(purchase.get("organizing_code").toString(), topDeveloperCode);

        commonGraphDto.getCompany().setId(companyData.get("organizing_code").toString());
        commonGraphDto.getCompany().setTitle(companyData.get("developer_name").toString());
        if (commonGraphDto.getTopCompany() != null && companyData.get("is_top_company_contain_developer").equals("是")) {
            commonGraphDto.getTopCompany().setId(companyData.get("top_organizing_code").toString());
            commonGraphDto.getTopCompany().setTitle(companyData.get("top_developer_name").toString());
        }

        commonGraphDto.setId(purchaseId);
        commonGraphDto.setTitle(purchase.get("title").toString());
        return commonGraphDto;
    }

    public CommonGraphDto getWinningBidGraph(String winningBidId) {
        Map<String, Object> purchase = developerCooperatorService.getWinBidById(winningBidId);
        if (purchase.get("id") == null) {
            throw new BusinessLogicException("找不到这个标");
        }
        Map<String, Object> companyData = developerService.getDeveloperMainData(purchase.get("organizing_code").toString());
        String topDeveloperCode;
        if (companyData.get("is_top_company_contain_developer").equals("是")) {
            topDeveloperCode = companyData.get("top_organizing_code").toString();
        } else {
            topDeveloperCode = companyData.get("organizing_code").toString();
        }

        CommonGraphDto commonGraphDto = getCommonGraph(purchase.get("organizing_code").toString(), topDeveloperCode);

        commonGraphDto.getCompany().setId(companyData.get("organizing_code").toString());
        commonGraphDto.getCompany().setTitle(companyData.get("developer_name").toString());
        if (commonGraphDto.getTopCompany() != null && companyData.get("is_top_company_contain_developer").equals("是")) {
            commonGraphDto.getTopCompany().setId(companyData.get("top_organizing_code").toString());
            commonGraphDto.getTopCompany().setTitle(companyData.get("top_developer_name").toString());
        }

        commonGraphDto.setId(winningBidId);
        commonGraphDto.setTitle(purchase.get("title").toString());
        return commonGraphDto;
    }

    public CommonGraphDto getTakenLandGraph(String takenLandId) {
        GetDetailDataRequestDto getDetailDataRequestDto = new GetDetailDataRequestDto();
        getDetailDataRequestDto.setId(takenLandId);
        Map<String, Object> takenLand = developerTakeLandService.getLandDetail(getDetailDataRequestDto);
        if (takenLand.get("id") == null) {
            throw new BusinessLogicException("找不到这个拿地");
        }
        Map<String, Object> companyData = (Map<String, Object>) takenLand.get("company");
        String topDeveloperCode;
        if (companyData.get("is_top_company_contain_developer").equals("是")) {
            topDeveloperCode = companyData.get("top_organizing_code").toString();
        } else {
            topDeveloperCode = companyData.get("organizing_code").toString();
        }

        CommonGraphDto commonGraphDto = getCommonGraph(takenLand.get("organizing_code").toString(), topDeveloperCode);

        commonGraphDto.getCompany().setId(companyData.get("organizing_code").toString());
        commonGraphDto.getCompany().setTitle(companyData.get("developer_name").toString());
        if (commonGraphDto.getTopCompany() != null && companyData.get("is_top_company_contain_developer").equals("是")) {
            commonGraphDto.getTopCompany().setId(companyData.get("top_organizing_code").toString());
            commonGraphDto.getTopCompany().setTitle(companyData.get("top_developer_name").toString());
        }

        commonGraphDto.setId(takenLandId);
        commonGraphDto.setTitle(takenLand.get("land_title").toString());
        return commonGraphDto;
    }


    public CommonGraphDto getCommencePermitGraph(String CommencePermitId) {
        GetDetailDataRequestDto getDetailDataRequestDto = new GetDetailDataRequestDto();
        getDetailDataRequestDto.setId(CommencePermitId);
        Map<String, Object> commencePermitDetail = developerCommencePermitService.getCommencePermitDetail(getDetailDataRequestDto);
        if (commencePermitDetail.get("id") == null) {
            throw new BusinessLogicException("找不到这个开工");
        }
        Map<String, Object> companyData = (Map<String, Object>) commencePermitDetail.get("build_company");
        String topDeveloperCode;
        if (companyData.get("is_top_company_contain_developer").equals("是")) {
            topDeveloperCode = companyData.get("top_organizing_code").toString();
        } else {
            topDeveloperCode = companyData.get("organizing_code").toString();
        }

        CommonGraphDto commonGraphDto = getCommonGraph(commencePermitDetail.get("organizing_code").toString(), topDeveloperCode);

        commonGraphDto.getCompany().setId(companyData.get("organizing_code").toString());
        commonGraphDto.getCompany().setTitle(companyData.get("developer_name").toString());
        if (commonGraphDto.getTopCompany() != null && companyData.get("is_top_company_contain_developer").equals("是")) {
            commonGraphDto.getTopCompany().setId(companyData.get("top_organizing_code").toString());
            commonGraphDto.getTopCompany().setTitle(companyData.get("top_developer_name").toString());
        }

        commonGraphDto.setId(CommencePermitId);
        commonGraphDto.setTitle(commencePermitDetail.get("project_name").toString());
        return commonGraphDto;
    }

    public CommonGraphDto getMohurdProjectGraph(String projectId) {
        GetDetailDataRequestDto getDetailDataRequestDto = new GetDetailDataRequestDto();
        getDetailDataRequestDto.setId(projectId);
        Map<String, Object> projectDetail = mohurdProjectService.getProjectDetail(getDetailDataRequestDto);
        if (projectDetail.get("id") == null) {
            throw new BusinessLogicException("找不到这个在建项目");
        }
        String[] organizingCodeArr = new String[0];
        if (projectDetail.get("organizing_code").getClass().isArray()) {
            organizingCodeArr = (String[]) projectDetail.get("organizing_code");
        }

        String[] topOrganizingCodeArr = new String[0];
        if (projectDetail.get("top_organizing_code").getClass().isArray()) {
            topOrganizingCodeArr = (String[]) projectDetail.get("top_organizing_code");
        }
        String organizingCode = organizingCodeArr.length > 0 ? organizingCodeArr[0] : "";
        String topOrganizingCode = topOrganizingCodeArr.length > 0 ? topOrganizingCodeArr[0] : "";
        CommonGraphDto commonGraphDto = getCommonGraph(organizingCode, topOrganizingCode);

        commonGraphDto.getCompany().setId(organizingCode);
        commonGraphDto.getCompany().setTitle(projectDetail.get("build_corp_name").toString());
        if (commonGraphDto.getTopCompany() != null) {
            commonGraphDto.getTopCompany().setId(topOrganizingCode);
            commonGraphDto.getTopCompany().setTitle(projectDetail.get("top_developer_name").toString());
        }

        commonGraphDto.setId(projectId);
        commonGraphDto.setTitle(projectDetail.get("prj_name").toString());
        return commonGraphDto;
    }
}
